package com.coco.seck.redisconfig;


import com.coco.common.constant.Constant;
import com.coco.seck.mapper.SeckillOrderMapper;
import com.coco.seck.pojo.TbSeckillGoods;
import com.coco.seck.pojo.TbSeckillOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author HanSama
 * @date 2021年07月19日 9:06
 */
@Component
public class RedisListener extends KeyExpirationEventMessageListener {


    @Autowired
    private SeckillOrderMapper seckillOrderMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    public RedisListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 获取过期的key
        String expiredKey = message.toString();
        // 判断是否是想要监听的过期key
        if (expiredKey.contains(Constant.OrderKeyConstant.WITH_ORDER_KEY)) {
            System.out.println("过期KEY："+expiredKey);
            String[] split = expiredKey.split(Constant.OrderKeyConstant.SUB_KEY);
            //获取货期的订单id
            long id = Long.parseLong(split[Constant.OrderKeyConstant.FIRST_KEY]);
            seckillOrderMapper.updateStatus(id, Constant.OrderStatus.STATUS_THREE);
            //获得秒杀商品id
            TbSeckillOrder seckillOrder =  seckillOrderMapper.findOneById(id);
            //redis秒杀商品数量回退
            redisTemplate.opsForValue().increment(Constant.RedisKeyConstant.GOODS_KEY_TEMPLATE+seckillOrder.getSeckillId());
            //从秒杀名单中去除该用户
            Map entries = redisTemplate.opsForHash().entries(Constant.RedisKeyConstant.GOODS_NUM_TEMPLATE+seckillOrder.getSeckillId());
            Integer num = (Integer) entries.get(Constant.RedisKeyConstant.USER_TEMPLATE + seckillOrder.getUserId());
            entries.put(Constant.RedisKeyConstant.USER_TEMPLATE+seckillOrder.getUserId(),num-1);
            redisTemplate.opsForHash().putAll(Constant.RedisKeyConstant.GOODS_NUM_TEMPLATE+seckillOrder.getSeckillId(),entries);
        }
    }


}
